package freespiritsocial.io.user.viewmodel

import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import freespiritsocial.io.user.data.model.bean.PlaceAutocompleteBean
import freespiritsocial.io.user.data.model.bean.PlaceAutocompleteBean.Companion.LOCATION_API
import freespiritsocial.io.user.network.apiService
import freespiritsocial.io.user.ui.helper.GoogleApiHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.callback.livedata.StringLiveData
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.ext.util.loge

@ExperimentalCoroutinesApi
class LocationViewModel: BaseViewModel() {
    val searchText = StringLiveData()
    val errorText = StringObservableField()
    val errorBtnText = StringObservableField()

    var googleApiHelper: GoogleApiHelper? = null

    private val _stateFlow = MutableStateFlow("")

    val googleSearchResultNetWork =
        // 避免在单位时间内，快输入造成大量的请求
        _stateFlow.debounce(1000)
            .flatMapLatest { s ->
                s.loge("csw")
                if (s.isEmpty()) {
                    emptyFlow()
                } else {
                    val list = arrayListOf<PlaceAutocompleteBean>()
                    list.addAll(apiService.locationTextSearch(query = s).results.map {
                        PlaceAutocompleteBean(it.place_id,it.name,it.formatted_address,type = LOCATION_API)
                    })
                    googleApiHelper!!.searchPlaces(s).toList(list)
                    list.asFlow()
                }
            }.catch {
                this.toString().loge("catch")
            }.asLiveData()


    fun search() {
        _stateFlow.value = searchText.value
    }

    fun nearbySearch(lat: Double,lng: Double,callback: (List<PlaceAutocompleteBean>) -> Unit) {
        requestNoCheck({
            apiService.nearbySearch(location = "$lat,$lng")
        },{ googleLocationBean ->
            callback(googleLocationBean.results.map { PlaceAutocompleteBean(it.place_id,it.name,"",LOCATION_API) })
        })
    }
}